<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>其他费用管理</title>
    <!-- 引入其它组件 -->
    <!-- 引入 layui -->
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/app.css">
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            padding: 20px;
            background-color: #f2f2f2;
            height: 100vh;
            overflow: hidden;
        }

        .container {
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            height: calc(100vh - 40px);
            display: flex;
            flex-direction: column;
        }

        .table-container {
            flex: 1;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            min-height: 0;
        }

        .table-wrapper {
            flex: 1;
            overflow: auto;
            border: 1px solid #e6e6e6;
            margin-bottom: 15px;
        }

        .layui-table {
            width: 100%;
            margin-bottom: 0;
        }

        .layui-table th {
            text-align: center;
            font-weight: bold;
            background-color: #f8f8f8;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .layui-table td {
            padding: 8px 12px;
        }

        .total-row {
            font-weight: bold;
            background-color: #e6f7ff !important;
            position: sticky;
            bottom: 0;
            z-index: 10;
        }

        .manual-row {
            background-color: #f6ffed !important;
        }

        .delete-btn {
            cursor: pointer;
        }

        .loading-mask {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }

        .button-container {
            flex-shrink: 0;
            padding-top: 15px;
            border-top: 1px solid #f0f0f0;
            text-align: center;
        }

        .status-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 5px;
        }

        .status-saved {
            background-color: #5FB878;
        }

        .status-unsaved {
            background-color: #FF5722;
        }

        /* 弹出窗口专用样式 */
        .dialog-input-group {
            display: flex;
            align-items: center;
            margin-bottom: 18px;
            min-height: 36px;
        }

        .dialog-input-prefix {
            width: 80px;
            padding-right: 12px;
            text-align: right;
            font-weight: bold;
            white-space: nowrap;
            flex-shrink: 0;
        }

        .dialog-input-content {
            flex: 1;
            display: flex;
            align-items: center;
        }

        .input-with-unit {
            display: flex;
            align-items: center;
            flex: 1;
        }

        .input-with-unit input {
            flex: 1;
        }

        .input-with-unit .unit {
            width: 60px;
            padding-left: 10px;
            white-space: nowrap;
        }

        .dialog-textarea-group {
            display: flex;
            margin-bottom: 15px;
            align-items: flex-start;
        }

        .dialog-textarea-prefix {
            width: 80px;
            padding-right: 12px;
            text-align: right;
            font-weight: bold;
            white-space: nowrap;
            flex-shrink: 0;
            padding-top: 8px;
        }

        .dialog-textarea-content {
            flex: 1;
        }
    </style>
</head>

<body>
    <div class="container" id="main-container">
        <!-- 加载遮罩层 -->
        <div class="loading-mask" id="loading-mask">
            <div class="layui-card">
                <div class="layui-card-body">
                    <i class="layui-icon layui-anim layui-anim-rotate layui-anim-loop">&#xe63d;</i>
                    <span style="margin-left: 10px;">正在加载项目数据...</span>
                </div>
            </div>
        </div>

        <div class="table-container">
            <div class="table-wrapper">
                <table class="layui-table" lay-size="sm" id="budget-table">
                    <colgroup>
                        <col width="3%">
                        <col width="20%">
                        <col width="20%">
                        <col width="8%">
                        <col width="8%">
                        <col width="8%">
                        <col width="15%">
                        <col width="6%">
                    </colgroup>
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th>费用名称</th>
                            <th>计算依据及方法</th>
                            <th>除税价（元）</th>
                            <th>增值税（元）</th>
                            <th>含税价（元）</th>
                            <th>备注</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="table-body">
                        <!-- 数据将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>

        </div>
        <!-- 关闭按钮 -->
        <div class="btn-container" style="text-align: center;">
            <button class="layui-btn layui-btn-primary" type="button" id="btn-close">关闭</button>
        </div>

    </div>

    <script src="/js/config/api.js"></script>
    <script src="/js/http.js"></script>
    <script src="/layui/layui.js"></script>

    <script>
        layui.use(['jquery', 'layer', 'form'], function () {
            var $ = layui.$;
            var layer = layui.layer;
            var form = layui.form;
            var manualRowCount = 0;
            var rateVat = 0.09;
            var rateSafe = 0.015;
            var designCode = getUrlParam("design_code");
            var designType = parseInt(getUrlParam("design_type"));

            // 状态管理变量
            var hasUnsavedChanges = false;
            var originalDataHash = "";

            // 表格数据
            var tableData = {
                staticRows: [],
                totalRow: [],
                manualRows: []
            };
            var totalResult = { totalTaxExcluded: 0, totalTax: 0, totalTaxIncluded: 0 };

            initPage();

            function initPage() {
                try {
                    // 后端获取总安装费（不含税）
                    http.get(API_CONFIG.ENDPOINTS.LOAD_OTHER_FEE, {
                        design_code: designCode,
                        design_type: designType
                    }).then(function (res) {
                        if (res.code === 0) {
                            const constructionCost = Number(res.data.construction_cost);
                            // 安全系数
                            rateSafe = Number(res.data.rate_safe);
                            // 增值税系数
                            rateVat = Number(res.data.rate_vat);

                            // 生成表格数据
                            generateTableData(constructionCost, res.data.other_fee);

                            // 隐藏加载遮罩
                            $('#loading-mask').hide();

                            // 初始加载后标记为已保存
                            markAsSaved();
                        }
                    });
                }
                catch (error) {
                    console.error("获取总安装费失败:", error);
                }

            }

            // 生成表格数据
            function generateTableData(constructionCost, otherFee) {
                // 计算安全生产费（建筑安装工程费×2.00%）
                console.log("安装费合计:", constructionCost);

                var safetyProductionCost = constructionCost * rateSafe;
                var safetyProductionTax = safetyProductionCost * rateVat;
                var safetyProductionTotal = safetyProductionCost + safetyProductionTax;

                // 静态数据行
                tableData.staticRows = [
                    { id: 1, name: '建设用地及综合赔补费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 2, name: '建设单位管理费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 3, name: '可行性研究费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 4, name: '研究试验费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 5, name: '勘察设计费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 5.1, name: '其中：勘察费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 5.2, name: '其中：设计费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 6, name: '环境影响评价费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 7, name: '劳动安全卫生评价费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 8, name: '建设工程监理费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 9, name: '安全生产费', basis: `建筑安装工程费×${(rateSafe * 100).toFixed(2)}%`, taxExcluded: safetyProductionCost, tax: safetyProductionTax, taxIncluded: safetyProductionTotal, remark: `建筑安装工程费: ${constructionCost.toFixed(2)}元`, isManual: false },
                    { id: 10, name: '工程质量监督费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 11, name: '工程定额测定费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 12, name: '引进技术及引进设备其它费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 13, name: '工程保险费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 14, name: '工程招标代理费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 15, name: '专利及专利技术使用费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false }
                ];

                // 初始化总计行
                tableData.totalRow = [
                    {
                        id: '',
                        name: '总计',
                        basis: '',
                        taxExcluded: totalResult.totalTaxExcluded.toFixed(2),
                        tax: totalResult.totalTax.toFixed(2),
                        taxIncluded: totalResult.totalTaxIncluded.toFixed(2),
                        remark: '',
                        isManual: false
                    }
                ];

                // 初始化手动行为空
                tableData.manualRows = [];
                var otherArray = (otherFee && Array.isArray(otherFee)) ? otherFee : [];
                for (let i = 0; i < otherArray.length; i++) {
                    const element = otherArray[i];
                    var taxIncluded = Number(element.tax_included);
                    var taxExcluded = taxIncluded / (1 + rateVat);
                    var tax = taxIncluded - taxExcluded;
                    addManualRow(element.name, element.basis, taxExcluded, tax, taxIncluded, element.remark);
                }

                // 渲染表格
                renderTable();
            }

            // 渲染表格
            function renderTable() {
                var tableBody = $('#table-body');
                tableBody.empty();

                // 添加静态行
                tableData.staticRows.forEach(row => {
                    var isSubItem = row.id.toString().includes('.');
                    var rowHtml = `
                        <tr${isSubItem ? ' style="background-color: #f9f9f9;"' : ''}>
                            <td>${isSubItem ? '' : Math.floor(row.id)}</td>
                            <td>${row.name}</td>
                            <td>${row.basis}</td>
                            <td style="text-align: right;">${row.taxExcluded.toFixed(2)}</td>
                            <td style="text-align: right;">${row.tax.toFixed(2)}</td>
                            <td style="text-align: right;">${row.taxIncluded.toFixed(2)}</td>
                            <td>${row.remark}</td>
                            <td></td>
                        </tr>
                    `;
                    tableBody.append(rowHtml);
                });

                // 计算总计
                calculateTotal();

                // 添加总计行
                tableData.totalRow.forEach(row => {
                    var rowHtml = `
                        <tr class="total-row" data-id="${row.id}">
                        <td></td>
                        <td>${row.name}</td>
                        <td>${row.basis}</td>
                        <td style="text-align: right;">${totalResult.totalTaxExcluded.toFixed(2)}</td>
                        <td style="text-align: right;">${totalResult.totalTax.toFixed(2)}</td>
                        <td style="text-align: right;">${totalResult.totalTaxIncluded.toFixed(2)}</td>
                        <td>${row.remark}</td>
                        <td></td>
                    </tr>
                    `;
                    console.log(rowHtml)
                    tableBody.append(rowHtml)
                });

                // 添加手动行
                tableData.manualRows.forEach(row => {
                    var rowHtml = `
                        <tr class="manual-row" data-id="${row.id}">
                            <td>${16 + tableData.manualRows.indexOf(row)}</td>
                            <td>${row.name}</td>
                            <td>${row.basis}</td>
                            <td style="text-align: right;">${row.taxExcluded.toFixed(2)}</td>
                            <td style="text-align: right;">${row.tax.toFixed(2)}</td>
                            <td style="text-align: right;">${row.taxIncluded.toFixed(2)}</td>
                            <td>${row.remark}</td>
                            <td>
                                <button class="layui-btn layui-btn-danger layui-btn-xs delete-btn" data-id="${row.id}">删除</button>
                            </td>
                        </tr>
                    `;
                    tableBody.append(rowHtml);
                });

                form.render();
            }

            // 计算总计
            function calculateTotal() {
                totalResult.totalTaxExcluded = 0;
                totalResult.totalTax = 0;
                totalResult.totalTaxIncluded = 0;

                // 计算静态行
                tableData.staticRows.forEach(row => {
                    totalResult.totalTaxExcluded += row.taxExcluded;
                    totalResult.totalTax += row.tax;
                    totalResult.totalTaxIncluded += row.taxIncluded;
                });

                // 计算手动行
                tableData.manualRows.forEach(row => {
                    totalResult.totalTaxExcluded += row.taxExcluded;
                    totalResult.totalTax += row.tax;
                    totalResult.totalTaxIncluded += row.taxIncluded;
                });
            }


            // 添加手动行到表格
            function addManualRow(name, basis, taxExcluded, tax, taxIncluded, remark) {
                manualRowCount++;

                var newRow = {
                    id: 'manual_' + manualRowCount,
                    name: name,
                    basis: basis,
                    taxExcluded: taxExcluded,
                    tax: tax,
                    taxIncluded: taxIncluded,
                    remark: remark,
                    isManual: true
                };

                // 添加到数据中
                tableData.manualRows.push(newRow);

                // 重新渲染表格
                renderTable();

                // 标记有未保存的更改
                markAsUnsaved();
            }

            // 工具函数
            function getUrlParam(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                return r ? decodeURIComponent(r[2]) : null;
            }

            $('#btn-close').click(function () {
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            });


        });
    </script>
</body>

</html>